package com.beichuan_travel.service.impl;

import com.beichuan_travel.interfaces.transform.PlanCovertBasic;
import com.beichuan_travel.mapper.PlanMapper;
import com.beichuan_travel.model.dto.PlanDTO;
import com.beichuan_travel.model.po.PlanPO;
import com.beichuan_travel.model.vo.PlanVO;
import com.beichuan_travel.service.PlanServcie;
import com.beichuan_travel.utils.ImgUtil;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

@Service("tripService")
public class PlanServiceImpl implements PlanServcie {

    @Resource
    PlanMapper planMapper;

    @Resource
    ImgUtil imgUtil;

    @Override
    public List<PlanVO> queryTripPerDay(Integer uid, String date) {
        List<PlanPO> poList = planMapper.queryByDate(uid, date);
        if (poList == null || poList.isEmpty()) {
            return null;
        }
        List<PlanVO> voList = PlanCovertBasic.INSTANCE.POtoCoertVO(poList);
        return voList;
    }

    @Override
    public int addTrip(PlanDTO planDTO, MultipartFile img, Integer uid) {
        String url = null;
        if (img == null) {
            url = imgUtil.renameUrl("plan", img.getOriginalFilename());
            imgUtil.transfor(img, url);
        }
        PlanPO po = PlanCovertBasic.INSTANCE.DTOtoCovertPO(planDTO);
        po.setImg("/picture" + url);
        return planMapper.addPlan(po);
    }

    @Override
    public int delTrip(Integer id) {
        return planMapper.delPlan(id);
    }

    @Override
    public Map<String, List<PlanVO>> list(int uid) {
        List<PlanPO> poList = planMapper.queryAll(uid);
        List<PlanVO> voList = PlanCovertBasic.INSTANCE.POtoCoertVO(poList);
        Map<String, List<PlanVO>> map = new HashMap<>();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        for (PlanVO vo : voList) {
            String day = simpleDateFormat.format(vo.getDate());
            if (!map.containsKey(day)) {
                List<PlanVO> list = new LinkedList<>();
                list.add(vo);
                map.put(day, list);
            } else {
                List<PlanVO> list = map.get(day);
                list.add(vo);
                map.put(day, list);
            }
        }
        return map;
    }

    @Override
    public Map<Integer, String> typeList() {
        Map<Integer, String> res = new HashMap<>();
        List<String> list = planMapper.listType();
        Integer i = 1;
        for (String str : list) {
            res.put(i++, str);
        }
        return res;
    }

    @Override
    public boolean checkMaxType(int type) {
        List<Integer> list = planMapper.checkTypeId();
        for (Integer i : list) {
            if (i == type) {
                return true;
            }
        }
        return false;
    }
}
